package com.wwz.frame.controller;

import com.wwz.frame.entity.ValidDemo;
import com.wwz.frame.entity.group.GroupA;
import com.wwz.frame.entity.group.GroupB;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.validator.constraints.Range;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.Min;
import javax.validation.groups.Default;
/**  
* @Description
* @Author wwz
* @Date 2019/09/24 
* @Param   
* @Return   
*/ 
@Api(value = "ValidController", tags = {"验证测试类"})
@RestController
@Slf4j
public class ValidController {
    /**
     * 基础验证方式 在验证的字段前加上@Valid或者@Validated 注解  增加 BindingResult 接收验证失败返回信息
     * */
//    @PostMapping("/validDemo")
//    public String validDemo1(@RequestBody(required = false) @Validated ValidDemo ValidDemo,BindingResult result) {
//        //判断是否返回异常
//        if (result.hasErrors()) {
//            //获取全部异常并返回
//            for (ObjectError error : result.getAllErrors()) {
//                log.error(error.getDefaultMessage());
//            }
//        }
//        return "";
//    }
//

    /**
     * 增加了全局异常捕获，不能加 BindingResult捕捉异常，直接去掉即可。
     */
    @ApiOperation("数据校验基本测试")
    @PostMapping("/validDemo")
    public String validDemo(@RequestBody(required = false) @Validated ValidDemo ValidDemo) {
        return "success";
    }

    // validDemo1 validDemo2 为分组验证
    @PostMapping("/validDemo1")
    public String validDemo1(@RequestBody(required = false) @Validated(GroupA.class) ValidDemo ValidDemo) {
        return "";
    }

    @PostMapping("/validDemo2")
    public String validDemo2(@RequestBody(required = false) @Validated({GroupB.class, Default.class}) ValidDemo ValidDemo) {

        return "";
    }

    /**
     * 只有少数对象，直接把参数写到Controller层，然后在Controller层进行验证
     * 该方法需要在controller上加@Valid 注解
     */
    @GetMapping(value = "/validDemo3")
    public String validDemo3(@Range(min = 1, max = 12, message = "月份只能1-12月")
                             @RequestParam(name = "mouth", required = true)
                                     int mouth,
                             @Min(value = 1, message = "年龄最小只能为1岁")
                             @RequestParam(name = "age", required = true)
                                     int age) {
        return age + "岁," + mouth + "个月";
    }
}
